import { computed, reactive, ref } from 'vue';
import vueRouter from '@/router';

const message = window['$message'];
const dialog = window['$dialog'];

export interface dialogParams {
  visible?: boolean;
  name?: string;
  detail?: any;
  title?: string;
  width?: number;
  placement?: string;
}

interface Option {
  onDelete?: Function;
  onBatchDelete?: Function;
}
export function useDataTable(option: Option = {}) {
  const router = vueRouter;
  const route = vueRouter.currentRoute.value;
  const formRef: any = ref(null);
  const dataTableRef = ref<any>({});
  const dialogState = reactive<dialogParams>({
    visible: false,
    name: '',
    detail: {},
    title: '',
    width: 840,
    placement: 'center',
  });
  const dialogStyle = computed(() => {
    return {
      width: dialogState.width + 'px',
    };
  });
  const dialogTap = ({
    name = '',
    detail = null,
    title = 'Dialog',
    width = 840,
    placement = 'bottom',
  }: dialogParams) => {
    dialogState.visible = true;
    dialogState.name = name;
    dialogState.title = title;
    dialogState.width = width;
    dialogState.placement = placement;
    detail && (dialogState.detail = JSON.parse(JSON.stringify(detail)));
  };
  const dialogClose = () => {
    dialogState.visible = false;
  };
  //批量删除
  function batchDeleteTap(selectKeys: any[]) {
    if (selectKeys.length === 0) {
      return;
    }
    window['$dialog'].info({
      title: '提示',
      content: `确定删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        option.onBatchDelete &&
          option.onBatchDelete({ ids: selectKeys.toString() }).then(() => {
            message.success('删除成功');
            dataTableRef.value.reload();
          });
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function goToDetailPageTap(name, id, query = {}) {
    router.push({
      name: name,
      params: { id: id },
      query: query,
    });
  }
  //删除
  function deleteTap(id: number) {
    dialog.info({
      title: '提示',
      content: `确定删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        option.onDelete &&
          option.onDelete({ id: id }).then(() => {
            message.success('删除成功');
            dataTableRef.value.reloadTable();
          });
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }
  const refreshData = () => {
    dialogState.visible = false;
    dataTableRef.value?.reloadTable();
  };
  return {
    formRef,
    router,
    route,
    dataTableRef,
    dialogState,
    dialogStyle,
    dialogTap,
    dialogClose,
    batchDeleteTap,
    goToDetailPageTap,
    deleteTap,
    refreshData,
  };
}
